﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using yzrilyzr.FAQ.client;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;

namespace FAQ_UI
{
	/// <summary>
	/// MsgList.xaml 的交互逻辑
	/// </summary>
	public partial class MsgList : Page, MsgPackReceiver
	{
		private List<FAQID> list = new List<FAQID>();
		private Dictionary<FAQID, MsgPack> msglist = new Dictionary<FAQID, MsgPack>();
		private FAQID toid;

		public MsgList()
		{
			InitializeComponent();
			DataContext = this;
			FAQUtil.client.addReceiver(this);
			update();
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.client.removeReceiver(this);
			//FAQUtil.eventBus.removeReceiver(this);
		}

		private void update()
		{
			list.Clear();
			list.AddRange(FAQUtil.client.getMsgList());
			msglist.Clear();
			foreach (var idItem in list)
			{
				MsgPack c = FAQUtil.client.getNewestMsg(idItem);
				if (c == null) continue;
				msglist[idItem] = c;
			}
			list.Sort((p1, p2) =>
			{
				MsgPack o1 = msglist[p1];
				MsgPack o2 = msglist[p2];
				if (o1 == null || o2 == null) return 0;
				if (o1.getTime() == o2.getTime()) return 0;
				return o1.getTime() > o2.getTime() ? -1 : 1;
			});
			myListView.notifyDataChanged();
		}

		public List<FAQID> BMsgListDataSource
		{ get { return list; } }

		public Holder BMsgListHolder
		{ get { return new Holder(); } }

		public void onItemClick(object listview, OnItemClickEvent e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_CHAT).setTo(list[e.index]));
			FAQUtil.client.setMsgIsRead(toid = list[e.index]);
			myListView.notifyDataChanged();
		}

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			if (mp.isMsg() || mp.getCmd() == C.USER_CACHE || mp.getCmd() == C.FRONTEND_FROM_ME_UPDATE)
			{
				if (toid != null)
				{
					FAQUtil.client.setMsgIsRead(toid);
				}
				Dispatcher.Invoke(new Action(() => { update(); }));
			}
		}

		public class Holder : FriendHolder
		{
			public override ViewHolder newInstance()
			{
				return new Holder();
			}

			public override void set(int i, object fAQID, IList datalist)
			{
				FAQID faqid = (FAQID)fAQID;
				Name.Text = FAQUtil.getCommNameOrName(faqid);
				MsgPack p = FAQUtil.client.getNewestMsg(faqid);
				Description.Text = ClientUtils.getNewestMsgStr(FAQUtil.client, p);
				Avatar.Drawable = FAQUtil.getAvatar(faqid);
				Time.Text = FAQUtil.getTimeStringByNow(p.getTime());
				OnlineState.Text =UUIDs.isPerson(faqid)? FAQClient.getOnlineState(faqid):"";
				int notRead = FAQUtil.client.getNotReadCount(faqid);
				Count.Text = notRead == 0 ? "" : notRead + "";
				Count.Background = notRead == 0 ? null : Theme.AccentBrush;
			}
		}
	}
}